package com.lingyu.jsjx.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.lingyu.jsjx.domain.StudentScore;
import com.lingyu.jsjx.domain.TeachingReflection;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.lingyu.jsjx.domain.Student;
import com.lingyu.jsjx.service.IStudentService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生信息Controller
 *
 * @author ruoyi
 * @date 2025-09-06
 */
@RestController
@RequestMapping("/student")
public class StudentController extends BaseController {
    @Autowired
    private IStudentService studentService;

    /**
     * 查询学生信息列表
     */
    @RequiresPermissions("system:student:list")
    @GetMapping("/list")
    public TableDataInfo list(Student student) {
        startPage();
        List<Student> list = studentService.selectStudentList(student);
        return getDataTable(list);
    }

    /**
     * 导出学生信息列表
     */
    @RequiresPermissions("system:student:export")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Student student) {
        List<Student> list = studentService.selectStudentList(student);
        ExcelUtil<Student> util = new ExcelUtil<Student>(Student.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @RequiresPermissions("system:student:query")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId) {
        return success(studentService.selectStudentByStudentId(studentId));
    }

    /**
     * 新增学生信息
     */
    @RequiresPermissions("system:student:add")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Student student) {
        return toAjax(studentService.insertStudent(student));
    }

    /**
     * 修改学生信息
     */
    @RequiresPermissions("system:student:edit")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Student student) {
        return toAjax(studentService.updateStudent(student));
    }

    /**
     * 删除学生信息
     */
    @RequiresPermissions("system:student:remove")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds) {
        return toAjax(studentService.deleteStudentByStudentIds(studentIds));
    }

    @Log(title = "学生信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, @RequestParam("scoreId") Long scoreId) throws Exception {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("导入文件不能为空");
        }

        // 检查文件格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))) {
            return AjaxResult.error("请上传Excel文件");
        }

        InputStream inputStream = null;
        Workbook workbook = null;

        try {
            inputStream = file.getInputStream();

            // 根据文件后缀创建不同的Workbook
            if (fileName.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }

            // 获取第一个sheet
            Sheet sheet = workbook.getSheetAt(0);

            // 读取表头（第一行）
            Row headerRow = sheet.getRow(0);
            List<String> headers = new ArrayList<>();
            for (Cell cell : headerRow) {
                headers.add(getCellValue(cell));
            }

            // 读取数据行（从第二行开始）
            List<Map<String, String>> dataList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Map<String, String> rowData = new HashMap<>();
                for (int j = 0; j < headers.size(); j++) {
                    Cell cell = row.getCell(j);
                    rowData.put(headers.get(j), getCellValue(cell));
                }
                dataList.add(rowData);
            }

            // 处理数据 - 这里可以根据实际需求进行数据处理
            processData(dataList, scoreId);

            return success("导入成功，共导入 " + dataList.size() + " 条数据");

        } catch (Exception e) {
            throw new Exception("导入失败：" + e.getMessage());
        } finally {
            // 关闭资源
            if (workbook != null) {
                workbook.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    // 获取单元格值的辅助方法
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 处理数字格式，避免科学计数法
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    // 数据处理方法 - 根据实际业务需求实现
    private void processData(List<Map<String, String>> dataList, Long scoreId) throws Exception {
        for (Map<String, String> rowData : dataList) {

            System.out.println(rowData);
            // 示例：检查必要字段
            if (!rowData.containsKey("姓名") || rowData.get("姓名").isEmpty()) {
                throw new Exception("姓名字段不能为空");
            }

            if (!rowData.containsKey("学号") || rowData.get("学号").isEmpty()) {
                throw new Exception("学号字段不能为空");
            }

            String name = rowData.get("姓名");
            String studentNo = rowData.get("学号");
            Student student = new Student();
            student.setStudentName(name);
            student.setStudentNo(studentNo);
            rowData.remove("姓名");
            rowData.remove("学号");
            student.setStudentScore(rowData.toString());
            student.setStudentScoreId(scoreId);
            int result = studentService.insertStudent(student);
            if (result < 0) {
                throw new Exception(name + "插入失败");
            }
        }
    }
}
